package org.xncj.Controller;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.constant.MessageConstant;
import org.entity.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.stylesheets.LinkStyle;
import org.xncj.MemberService;
import org.xncj.ReportService;
import org.xncj.SetMealService;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {
    @Resource
    ReportService reportService;
    @Resource
    MemberService memberService;
    @Resource
    SetMealService setMealService;

    @Value("${report_put_path}")
    private String reportPutPath;


    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
    @GetMapping("/exportBusinessReportPDF")
    public Result exportBusinessReportPDF(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取业务报告数据
        Map<String, Object> map = reportService.getBusinessReportData();

        // 获取热门套餐数据
        List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");

        // 设置jrxml和jasper文件路径
        String jrxmlPath = reportPutPath + "health_business3.jrxml";
        String jasperPath = reportPutPath + "health_business3.jasper";

        // 编译jrxml文件为jasper文件
        JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);

        // 填充报表
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, map, new JRBeanCollectionDataSource(hotSetmeal));

        // 获取响应输出流
        ServletOutputStream out = response.getOutputStream();
        // 设置响应内容类型为PDF
        response.setContentType("application/pdf");
        // 设置响应头，指定下载文件名
        response.setHeader("Content-Disposition", "attachment;filename=report.pdf");
        // 导出PDF到输出流
        JasperExportManager.exportReportToPdfStream(jasperPrint, out);

        // 返回null表示没有返回值
        return null;
    }



    @GetMapping("/exportBusinessReportExcel")
    public Result ExportBusinessReportExcel() {
        try {
            // 从服务中获取业务报告数据
            Map<String, Object> map = reportService.getBusinessReportData();

            // 提取数据
            String reportDate = (String) map.get("reportDate");
            Integer todayNewMember = (Integer) map.get("todayNewMember");
            Integer totalMember = (Integer) map.get("totalMember");
            Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");

            // 获取Excel模板路径并打开模板
            String templatePath = reportPutPath + "report_template.xlsx";
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(templatePath)));
            XSSFSheet sheet = workbook.getSheetAt(0);

            // 填充Excel模板中的数据
            // 填充日期
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);

            // 填充会员数据
            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);
            row.getCell(7).setCellValue(totalMember);

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);
            row.getCell(7).setCellValue(thisMonthNewMember);

            // 填充订单数据
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);
            row.getCell(7).setCellValue(todayVisitsNumber);

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            row.getCell(7).setCellValue(thisWeekVisitsNumber);

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            row.getCell(7).setCellValue(thisMonthVisitsNumber);

            // 填充热门套餐数据
            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) map.get("hotSetmeal");
            int num = 12;
            for (Map<String, Object> setmealMap : hotSetmeal) {
                String name = (String) setmealMap.get("name");
                Long setmeal_count = (Long) setmealMap.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) setmealMap.get("proportion");

                row = sheet.getRow(num++);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(String.valueOf(proportion));
            }

            // 将填充后的内容写回文件
            FileOutputStream stream = new FileOutputStream(templatePath);
            workbook.write(stream);

            // 关闭资源
            workbook.close();
            stream.close();

            // 返回成功结果和数据
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            // 捕获异常并打印堆栈跟踪
            e.printStackTrace();
            // 返回失败结果
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    @GetMapping("/getMemberReport")
    public Result getMemberReport() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -12);
        ArrayList<String> monthList = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            calendar.add(Calendar.MONTH, -i);
            SimpleDateFormat sdf = new SimpleDateFormat();
            String yearMouth = sdf.format(calendar.getTime());
            monthList.add(yearMouth);
        }
        try {
            HashMap<String, Object> map = new HashMap<>();
            map.put("monthList", monthList);

            List<Integer> memberCounts = memberService.findMemberCountByMouth(monthList);
            map.put("memberCount",memberCounts);
            return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }

    }
    @GetMapping("/getSetmealReport")
    public Result getSetMemberReport() {
        HashMap<String, Object> map = null;
        try {
            map = new HashMap<>();
            List<Map<String,Object>> list = setMealService.findSetmealCount();
            map.put("setmealCount",list);
            ArrayList<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> m : list){
                String name = (String) m.get("name");
                setmealNames.add(name);
            }
            map.put("setmealNames",setmealNames);
            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }
}
